const jwt = require('jsonwebtoken');

/**
 * 生成简单JWT令牌（1小时有效期）
 */
const generateToken = (user) => {
  const payload = {
    userId: user._id,
    email: user.email,
    name: user.name,
  };

  return jwt.sign(payload, process.env.JWT_SECRET || 'your-secret-key', {
    expiresIn: '1h',
  });
};

/**
 * 生成令牌对象（兼容现有代码）
 */
const generateTokens = (user) => {
  const accessToken = generateToken(user);

  return {
    accessToken,
    tokenType: 'Bearer'
  };
};

/**
 * 验证JWT令牌
 */
const verifyToken = (token) => {
  try {
    return jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new Error('令牌已过期');
    } else if (error.name === 'JsonWebTokenError') {
      throw new Error('无效的令牌');
    } else {
      throw error;
    }
  }
};

/**
 * 从请求头中提取令牌
 */
const extractTokenFromHeader = (authHeader) => {
  if (!authHeader) {
    throw new Error('缺少授权头');
  }

  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    throw new Error('无效的授权头格式');
  }

  return parts[1];
};

module.exports = {
  generateToken,
  generateTokens,
  verifyToken,
  extractTokenFromHeader
}; 